#!/usr/bin/python
"""
Set the wallpaper as the picture got from national geographic picture of the day
by xpwang@bea.com
FIXME: Needs to set the registry to keep the wallpaper setting after restart system
"""
import ctypes
import calendar
import urllib
import socket
import os
import time

STOREDIR = os.path.expanduser("~") + '/wallpaper/pod/'
DOWNLOADED = 0

def setWallPaper(imagePath):
	if os.name=="nt":
		"""Given a path to an image, convert it to bmp and set it as wallpaper"""
		bmpImage = Image.open(imagePath)
		newPath = STOREDIR + 'mywallpaper.bmp'
		bmpImage.save(newPath, "BMP")
		setWallpaperFromBMP(newPath)
	elif os.name=="posix": 
		try:
			os.system("gconftool-2 -t string -s /desktop/gnome/background/picture_filename \""+imagePath+"\" -s /desktop/gnome/background/picture_options stretched")
		except:
			os.system("dcop kdesktop KBackgroundIface setWallpaper \""+imagePath+"\" 7") 
    
def getPicture():
    try:
        sock = urllib.urlopen("http://lava.nationalgeographic.com/cgi-bin/pod/PhotoOfTheDay.cgi")
        htmlSource = sock.read()
        sock.close()    
        pos1 = htmlSource.find('Enlarge</a>')
        pos2 = htmlSource.find('Wallpaper</a>')
        page2 = htmlSource[pos1+50:pos2-2]
        pageurl = 'http://photography.nationalgeographic.com'+page2
        print pageurl
        
        sock = urllib.urlopen(pageurl)
        htmlSource = sock.read()
        sock.close()    
        pos1 = htmlSource.find('art-icon-wallpaper-1280.gif')
        pos2 = htmlSource.find('1280 x 1024 pixels')
        filename = htmlSource[pos1+42:pos2-2]
        print filename
        fileurl = 'http://photography.nationalgeographic.com'+filename
        onlyfile = filename[filename.rfind("/")+1:];
        print onlyfile
        fname = STOREDIR + onlyfile
        if not os.path.exists(fname):
            print 'file not retrieved'
            urllib.urlretrieve(fileurl, fname)
            print 'got the picture from ' + fileurl
        else:
            print 'The file is retrieved'
        return fname
    except Error:
        print "fail to getting picture of ",yy,mm,dd
        pass
    
    return fname

def setWallpaperOfToday():
    #filename  = getPicture()
    filename  = getPicture()
    print 'the filename is ' + filename
    setWallPaper(filename)

def prepare():
    #prepare the directory
    if not os.path.exists(STOREDIR):
        print 'going to make dir ' + STOREDIR
        os.makedirs(STOREDIR)
    print 'prepare done ...'

prepare()
setWallpaperOfToday()

print 'Wallpaper set ok!'
